<?php

FLEA::loadClass('FLEA_Controller_Action');

class Controller_Upload extends FLEA_Controller_Action
{

	function actionIndex()
	{
		// TODO 检查$_GET['album_id']是否合法
		$tb_albums =& FLEA::getSingleton('Table_Albums');
		/*@var $tb_albums Table_Albums*/
		$album = $tb_albums->find($_GET['album_id']);
		
		$viewdata = array(
			'title' => '上传图片',
			'album_id' => $album['album_id'],
			'album_name' => $album['name'],
	    );
		$this->_executeView('Upload.html', $viewdata);				
	}
	
	
	// 完成上传并返回缩略图地址
	function actionUpload(){
	    $key = 'Filedata';
	    $uploader =& FLEA::getSingleton('FLEA_Helper_FileUploader');
	    /* @var $uploader FLEA_Helper_FileUploader */
	    if (!$uploader->existsFile($key)) {
	        log_message('无效的上传', 'warning');
	        return;
	    }
	
	    $postfile =& $uploader->getFile($key);
	    if (!$postfile->check('.jpg/.jpeg/.png/.gif', 4000 * 1024)) {
	        log_message('上传的文件类型不正确', 'warning');
	        return;
	    }
	    
	    // 获取用户名
	    $tb_albums =& FLEA::getSingleton('Table_Albums');
		/*@var $tb_albums Table_Albums*/
	    $album = $tb_albums->find($_POST['album_id']);
	    $user = $album['member_id'];
	    
	    // 设置图片文件夹位置
	    $prefix = date('Y-m');
        $photoDir = FLEA::getAppInf('uploadDir') . DS . $user . DS . $prefix;
		
        // 创建需要的目录
        FLEA::loadHelper('file');
        mkdirs($photoDir);
        
        // 文件名根据当前时间和上传文件的临时文件名生成，确保不会产生重复的文件名
        $basename = md5(time() . $postfile->getTmpName());
        $photoFilename = $basename . '.' . $postfile->getExt();
        $thumbFilename = $basename . '_small.jpg';
        
        // 生成缩略图
        FLEA::loadHelper('image');
        $image =& FLEA_Helper_Image::createFromFile($postfile->getTmpName(), $postfile->getExt());
        $image->crop(120, 120, true, true);
        $image->saveAsJpeg($photoDir . DS . $thumbFilename);
        $image->destory();

        // 保存原始相片
        $postfile->move($photoDir . DS . $photoFilename);
        
        // 保存图片记录到数据库
        $tb_photos =& FLEA::getSingleton('Table_Photos');
        /*@var $tb_photos Table_Photos*/
        $photo = array(
        	'album_id' => $album['album_id'],
        	'photo' => $photoFilename,
        	'name' => $postfile->getFilename()
        );
        $tb_photos->create($photo);
        
        // 更新相册的封面图片
        $album['coverpic'] = $photoDir . DS . $thumbFilename;
        $tb_albums->update($album);
        
        // 返回缩略图地址
        echo $album['coverpic'];
	}
	
	
	
}

?>